﻿using System;
using MassTransit;
using MassTransit.RabbitMqTransport;
using Microsoft.Extensions.DependencyInjection;
using RabbitMQ.Client;
using Shared.Service.EventBus.Events;
using Shared.Service.EventBus.RabbitMq;

namespace Shared.Service.EventBus
{
    public static class DistributedBusExtension
    {
        public static void AddDistributedBus(
            this IServiceCollection services,
            EventBusSetting busConfig,
            Action<IRabbitMqBusFactoryConfigurator> factoryConfigurator)
        {
            services.AddMassTransit(x =>
                x.UsingRabbitMq((context, cfg) =>
                {
                    cfg.Host(busConfig.RabbitMqUri, h =>
                    {
                        h.Username(busConfig.UserName);
                        h.Password(busConfig.Password);
                    });

                    cfg.Message<ExternalEvent>(m =>
                    {
                        m.SetEntityName(busConfig.Exchange);
                    });
                    cfg.Publish<ExternalEvent>(p => p.ExchangeType = ExchangeType.Topic);

                    factoryConfigurator?.Invoke(cfg);

                    //cfg.Send<ExternalEvent>(s =>
                    //{
                    //    s.UseRoutingKeyFormatter(c => "marketing");
                    //});
                }));

            services.Configure<EventBusSetting>(configureOptions: e =>
            {
                e.Server = busConfig.Server;
                e.UserName = busConfig.UserName;
                e.Password = busConfig.Password;
                e.VHost = busConfig.VHost;
                e.Exchange = busConfig.Exchange;
                e.Port = busConfig.Port;
            });

            services.AddTransient<IDistributedBus, DistributedEventBus>();
            services.AddMassTransitHostedService();
        }
    }
}
